package com.sangeng.run;

import com.sangeng.config.RedisCache;
import com.sangeng.entity.Article;
import com.sangeng.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Component
//程序运行时将浏览量存入redis中
public class ViewCountRunner implements CommandLineRunner {
    @Autowired
    ArticleService articleService;
    @Autowired
    RedisCache redisCache;
    @Override
    public void run(String... args) throws Exception {
        //从数据库中查询数据，该字段在article中有，需要id和viewVCount
        List<Article> articles = articleService.getBaseMapper().selectList(null);
        Map<String, Integer> viewCountMap = articles.stream()
                //将文章id作为key（需要转化为Srting），以viewCount作为值（需要转换为integer，因为需要加一）
                .collect(Collectors.toMap(article -> article.getId().toString(),
                            article -> article.getViewCount().intValue()));
        //存储到redis中
        redisCache.setCacheMap("article:viewCount",viewCountMap);
        //将数据存入redis中

    }
}
